import React, { useRef, useState, useEffect } from 'react';
import { Button, message, Space, Typography, Modal, Form, InputNumber, Input, Select, Tag, Tooltip } from 'antd';
import { PlusOutlined, StopOutlined, CheckCircleOutlined, ExclamationCircleOutlined, EyeOutlined, DeleteOutlined, KeyOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import * as cardController from '@/services/backend/cardController';
import * as adminCustomerController from '@/services/backend/adminCustomerController';
import * as depositController from '@/services/backend/depositController';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { confirm } = Modal;

const CardManage: React.FC = () => {
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [lossModalVisible, setLossModalVisible] = useState<boolean>(false);
  const [lossRecordModalVisible, setLossRecordModalVisible] = useState<boolean>(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState(false);
  const [currentCard, setCurrentCard] = useState<any>(null);
  const [customers, setCustomers] = useState<any[]>([]);
  const [deposits, setDeposits] = useState<any[]>([]);
  const [customerLoading, setCustomerLoading] = useState(false);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [lossForm] = Form.useForm();
  const [passwordForm] = Form.useForm();

  // 调试：检查token
  useEffect(() => {
    const token = localStorage.getItem('token');
    const currentUser = localStorage.getItem('currentUser');
    console.log('Debug - Token:', token);
    console.log('Debug - CurrentUser:', currentUser);
    if (!token) {
      message.error('未找到登录token，请重新登录');
    }
  }, []);

  // 获取客户列表
  const fetchCustomers = async () => {
    setCustomerLoading(true);
    try {
      const response = await adminCustomerController.pageCustomers({
        page: 1,
        pageSize: 1000
      });
      if (response.code === 1) {
        setCustomers(response.data.records || []);
      } else {
        message.error('获取客户列表失败');
      }
    } catch (error) {
      console.error('获取客户列表失败:', error);
    } finally {
      setCustomerLoading(false);
    }
  };

  // 获取存款产品列表
  const fetchDeposits = async () => {
    try {
      const response = await depositController.getDepositPage({
        page: 1,
        size: 1000
      });
      if (response.code === 1) {
        setDeposits(response.data.records || []);
      } else {
        message.error('获取存款产品列表失败');
      }
    } catch (error) {
      console.error('获取存款产品列表失败:', error);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchCustomers();
    fetchDeposits();
  }, []);

  // 创建银行卡
  const handleCreate = async (values: any) => {
    if (values.openMoney < 1) {
      message.error('开户金额不得低于1元');
      return;
    }
    setLoading(true);
    try {
      // 获取选中用户的身份证号
      const selectedUser = customers.find(customer => customer.userId === values.userId);
      if (!selectedUser) {
        message.error('请选择用户');
        return;
      }

      // 构建请求参数
      const requestData = {
        pid: selectedUser.pid,
        depositId: values.depositId,
        currency: values.currency || 'RMB',
        openMoney: values.openMoney,
      };

      const response = await cardController.createCard(requestData);
      
      if (response.code === 1) {
        message.success('银行卡创建成功！');
        setCreateModalVisible(false);
        form.resetFields();
        actionRef.current?.reload();
      } else {
        message.error(response.msg || '创建失败');
      }
    } catch (error) {
      console.error('创建银行卡失败:', error);
      message.error('创建失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  // 挂失/解挂银行卡
  const handleReportLoss = async (cardId: string) => {
    try {
      await cardController.toggleReportLoss(cardId, 1);
      message.success('银行卡挂失成功！');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('挂失银行卡失败:', error);
      message.error(error.message || '挂失失败，请重试');
    }
  };

  const handleUnreportLoss = async (cardId: string) => {
    try {
      await cardController.toggleReportLoss(cardId, 0);
      message.success('银行卡解挂成功！');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('解挂银行卡失败:', error);
      message.error(error.message || '解挂失败，请重试');
    }
  };

  // 删除银行卡
  const handleDelete = async (cardId: string) => {
    try {
      const response = await cardController.deleteCard(cardId);
      message.success('银行卡删除成功！');
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('删除银行卡失败:', error);
      const errorMessage = error.message || '删除失败，请重试';
      message.error(errorMessage);
    }
  };

  // 显示挂失记录
  const showLossRecord = (record: any) => {
    setCurrentCard(record);
    setLossRecordModalVisible(true);
  };

  // 修改银行卡密码
  const handleUpdatePassword = async (values: any) => {
    try {
      const response = await cardController.updateCardPassword({
        cardId: currentCard.cardId,
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
      });
      
      if (response.code === 1) {
        message.success('密码修改成功');
        setPasswordModalVisible(false);
        passwordForm.resetFields();
      } else {
        message.error(response.msg || '密码修改失败');
      }
    } catch (error: any) {
      console.error('修改密码失败:', error);
      message.error(error.message || '修改失败，请重试');
    }
  };

  // 显示修改密码模态框
  const showPasswordModal = (record: any) => {
    setCurrentCard(record);
    setPasswordModalVisible(true);
  };

  // 表格列定义
  const columns: ProColumns<any>[] = [
    {
      title: '银行卡号',
      dataIndex: 'cardId',
      key: 'cardId',
      width: 200,
      fixed: 'left',
    },
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '余额',
      dataIndex: 'balance',
      key: 'balance',
      width: 120,
      hideInSearch: true,
      render: (_, record) => `¥${record.balance?.toFixed(2) || '0.00'}`,
    },
    {
      title: '货币',
      dataIndex: 'currency',
      key: 'currency',
      width: 80,
      hideInSearch: true,
    },
    {
      title: '存款业务',
      dataIndex: 'depositName',
      key: 'depositName',
      width: 150,
      hideInSearch: true,
      render: (depositName) => depositName || '-',
    },
    {
      title: '状态',
      dataIndex: 'isReportLoss',
      key: 'isReportLoss',
      width: 100,
      valueType: 'select',
      valueEnum: {
        0: { text: '正常', status: 'Success' },
        1: { text: '已挂失', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={record.isReportLoss === 1 ? 'red' : 'green'}>
          {record.isReportLoss === 1 ? '已挂失' : '正常'}
        </Tag>
      ),
    },
    {
      title: '开卡时间区间',
      dataIndex: 'openTimeRange',
      valueType: 'dateRange',
      hideInTable: true,
      search: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      valueType: 'dateTime',
      hideInSearch: true,
      render: (_, record) => record.createTime ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => showLossRecord(record)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            icon={<KeyOutlined />}
            onClick={() => showPasswordModal(record)}
          >
            修改密码
          </Button>
          {record.isReportLoss === 0 ? (
            <Tooltip title="挂失银行卡">
              <Button
                type="link"
                danger
                icon={<StopOutlined />}
                onClick={() => {
                  confirm({
                    title: '确认挂失',
                    content: `确定要挂失银行卡 ${record.cardId} 吗？`,
                    onOk: () => handleReportLoss(record.cardId),
                  });
                }}
              >
                挂失
              </Button>
            </Tooltip>
          ) : (
            <Tooltip title="解挂银行卡">
              <Button
                type="link"
                icon={<CheckCircleOutlined />}
                onClick={() => {
                  confirm({
                    title: '确认解挂',
                    content: `确定要解挂银行卡 ${record.cardId} 吗？`,
                    onOk: () => handleUnreportLoss(record.cardId),
                  });
                }}
              >
                解挂
              </Button>
            </Tooltip>
          )}
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => {
              confirm({
                title: '确认删除',
                content: `确定要删除银行卡 ${record.cardId} 吗？\n注意：只有余额为1元或以下的银行卡才能删除。`,
                onOk: () => handleDelete(record.cardId),
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 获取表格数据
  const fetchTableData = async (params: any) => {
    try {
      const { openTimeRange, current, pageSize, ...rest } = params;
      console.log('Debug - CardManage params:', params);
      console.log('Debug - CardManage openTimeRange:', openTimeRange);
      
      const requestParams = {
        page: params.current || 1,
        size: params.pageSize || 10,
        cardId: params.cardId,
        userId: params.userId,
        isReportLoss: params.isReportLoss,
        startTime: openTimeRange?.[0]?.format('YYYY-MM-DD'),
        endTime: openTimeRange?.[1]?.format('YYYY-MM-DD'),
      };
      
      console.log('Debug - CardManage requestParams:', requestParams);
      
      const response = await cardController.getCardPage(requestParams);
      console.log('Debug - CardManage response:', response);

      if (response.code === 1) {
        return {
          data: response.data.records || [],
          success: true,
          total: response.data.total || 0,
        };
      } else {
        message.error(response.msg || '获取数据失败');
        return {
          data: [],
          success: false,
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  return (
    <PageContainer>
      <ProTable<any>
        headerTitle="银行卡管理"
        actionRef={actionRef}
        rowKey="cardId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            icon={<PlusOutlined />}
            onClick={() => setCreateModalVisible(true)}
          >
            创建银行卡
          </Button>,
        ]}
        request={fetchTableData}
        columns={columns}
        scroll={{ x: 1200 }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 创建银行卡模态框 */}
      <Modal
        title="创建银行卡"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Form.Item
            name="userId"
            label="选择用户"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              placeholder="请选择用户"
              loading={customerLoading}
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={customers.map(customer => ({
                value: customer.userId,
                label: `${customer.userName} (${customer.pid})`
              }))}
            />
          </Form.Item>

          <Form.Item
            name="depositId"
            label="存款产品"
            rules={[{ required: true, message: '请选择存款产品' }]}
          >
            <Select
              placeholder="请选择存款产品"
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={deposits.map(deposit => ({
                value: deposit.depositId,
                label: deposit.depositName
              }))}
            />
          </Form.Item>

          <Form.Item
            name="currency"
            label="货币类型"
            initialValue="RMB"
          >
            <Select>
              <Select.Option value="RMB">人民币 (RMB)</Select.Option>
              <Select.Option value="USD">美元 (USD)</Select.Option>
              <Select.Option value="EUR">欧元 (EUR)</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="openMoney"
            label="开户金额"
            rules={[
              { required: true, message: '请输入开户金额' },
              { type: 'number', min: 1, message: '开户金额不得低于1元' }
            ]}
          >
            <InputNumber 
              placeholder="请输入开户金额" 
              min={1} 
              precision={2}
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                创建
              </Button>
              <Button onClick={() => {
                setCreateModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 挂失记录模态框 */}
      <Modal
        title="银行卡详情"
        open={lossRecordModalVisible}
        onCancel={() => setLossRecordModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setLossRecordModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {currentCard && (
          <div>
            <p><strong>银行卡号：</strong>{currentCard.cardId}</p>
            <p><strong>用户ID：</strong>{currentCard.userId}</p>
            <p><strong>存款业务：</strong>{currentCard.depositName || '-'}</p>
            <p><strong>余额：</strong>¥{currentCard.balance?.toFixed(2) || '0.00'}</p>
            <p><strong>货币：</strong>{currentCard.currency}</p>
            <p><strong>状态：</strong>{currentCard.isReportLoss === 1 ? '已挂失' : '正常'}</p>
            <p><strong>创建时间：</strong>{currentCard.createTime ? dayjs(currentCard.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'}</p>
          </div>
        )}
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改银行卡密码"
        open={passwordModalVisible}
        onCancel={() => {
          setPasswordModalVisible(false);
          passwordForm.resetFields();
        }}
        footer={null}
        width={400}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleUpdatePassword}
        >
          <Form.Item
            name="oldPassword"
            label="原密码"
            rules={[
              { required: true, message: '请输入原密码' },
              { pattern: /^\d{6}$/, message: '密码必须是6位数字' }
            ]}
          >
            <Input.Password placeholder="请输入原密码" maxLength={6} />
          </Form.Item>

          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { pattern: /^\d{6}$/, message: '密码必须是6位数字' }
            ]}
          >
            <Input.Password placeholder="请输入新密码" maxLength={6} />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              { pattern: /^\d{6}$/, message: '密码必须是6位数字' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请再次输入新密码" maxLength={6} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确认修改
              </Button>
              <Button onClick={() => {
                setPasswordModalVisible(false);
                passwordForm.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CardManage; 